package com.summer.safe.controller.system;

import com.summer.safe.base.BaseController;
import com.summer.safe.base.TreeNode;
import com.summer.safe.config.annotation.ResultWrapper;
import com.summer.safe.config.result.ResultCode;
import com.summer.safe.system.entity.Area;
import com.summer.safe.system.service.AreaService;
import com.summer.safe.utils.StringUtils;
import com.summer.safe.utils.ToolUtil;
import com.summer.safe.utils.TreeUtils;
import com.summer.safe.utils.UserUtils;
import com.summer.safe.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 区域Controller
 *
 */
@Controller
@RequestMapping(value = "/sys/area")
public class AreaController extends BaseController {
    private String PREFIX = "/system/area/";
    @Autowired
    private AreaService areaService;

    @ModelAttribute("area")
    public Area get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return areaService.get(id);
        } else {
            return new Area();
        }
    }

    @RequiresPermissions("sys:area:view")
    @GetMapping
    public String index() {
        return PREFIX + "arealist.html";
    }


    @RequestMapping("/areaData")
    @ResultWrapper(ResultCode.SUCCESS_QUERY)
    public List<Area> list(Area area) {
        List<Area> list = areaService.findList(area);
        return list;
    }

    @RequiresPermissions("sys:area:edit")
    @GetMapping(value = "form")
    public String form(Area area, Model model) {
        if (area.getParent() == null || area.getParent().getId() == null) {
            area.setParent(UserUtils.getUser().getOffice().getArea());
        }else {
            area.setParent(areaService.get(area.getParent().getId()));

        }
        model.addAttribute("area", area);
        return PREFIX + "areaform.html";
    }


    @PostMapping(value = "save")
    @ResultWrapper(ResultCode.SUCCESS_SAVE)
    public void save(Area area) {
        //判断是否为演示模式
        ToolUtil.DemoMode();
        areaService.save(area);
    }


    @RequestMapping(value = "delete")
    @ResultWrapper(ResultCode.SUCCESS_DELETE)
    public void delete(Area area) {
        areaService.delete(area);
    }


    /**
     * 区域的
     * @param isAll
     * @return
     */
    @ResponseBody
    @GetMapping(value = "treeData")
    public List<TreeNode> treeData(@RequestParam(required = false) Boolean isAll) {
        List<Area> list = areaService.findList(isAll);
        return TreeUtils.treeNodes(list);
        /*return TreeUtils.treeNodes(list).stream().map(treeNode -> {
            treeNode.setIcon("../../static/images/icon1.png");
            return treeNode;
        }).collect(Collectors.toList());*/
    }
}
